package org.tang.springcloudvv.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 增加本类后，可能导致原项目启动出错，提示找到2个sqlSessionFactory
 * 解决：原项目MyBatisConfig的sqlSessionFactory加上@Primary
 */
@Configuration
@MapperScan(basePackages = {Log4jSqlSessionFactoryConfig.CLASTER_PACKAGE}, sqlSessionFactoryRef = "log4jSqlSessionFactory")
public class Log4jSqlSessionFactoryConfig {
	
	//扫描从数据源mapper接口所在的包
    static final String CLASTER_PACKAGE = "org.tang.springcloudvv.mapperextend";
    //扫描从数据源xml文件
    static final String MAPPER_LOCATION = "classpath:mapper/log/*.xml";
    
	private Logger logger = LoggerFactory.getLogger(Log4jSqlSessionFactoryConfig.class);

    @Bean(name = "log4jSqlSessionFactory")
    public SqlSessionFactory log4jSqlSessionFactory(DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(Log4jSqlSessionFactoryConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
    
}
